package com.madi.company.ui.main.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.jaydenxiao.common.base.BaseActivity;
import com.madi.company.R;
import com.madi.company.bean.JobTypeEntity;
import com.madi.company.contract.JobTypeContract;
import com.madi.company.model.JobTpyeModel;
import com.madi.company.presenter.JobTypePresenter;
import com.madi.company.ui.main.adapter.JobTypeAdapter;
import com.madi.company.utils.SerializableMap;
import com.madi.company.widget.ClearEditText;
import com.timehop.stickyheadersrecyclerview.StickyRecyclerHeadersDecoration;
import com.timehop.stickyheadersrecyclerview.StickyRecyclerHeadersTouchListener;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.OnClick;

import static com.madi.company.R.id.CheckBoxPositionType;
import static com.madi.company.R.id.linearLayoutAddPositionTypeTxt;


/**
 * Created by 丁宁
 * on 2016/12/9.
 * 职位类别 列表界面
 *
 * ++++ 目前问题 搜索结果 + 条目点击冲突的问题没处理完全 中英文的数据也没处理
 */
public class JobTypeActivity extends BaseActivity<JobTypePresenter, JobTpyeModel> implements JobTypeContract.View {

    @Bind(R.id.backBtn)
    LinearLayout mBackBtn;
    @Bind(R.id.title)
    TextView mTitle;
    @Bind(R.id.textOne)
    TextView mTextOne;
    @Bind(R.id.filter_edit)
    ClearEditText mFilterEdit;
    @Bind(R.id.Btn_ProfessionType)
    Button mBtnProfessionType;
    @Bind(R.id.job_type_select_number)
    TextView mJobTypeSelectNumber;
    @Bind(CheckBoxPositionType)
    CheckBox mCheckBoxPositionType;
    @Bind(linearLayoutAddPositionTypeTxt)
    LinearLayout mLinearLayoutAddPositionTypeTxt;
    @Bind(R.id.list)
    RecyclerView mListView;
    @Bind(R.id.activity_job_type)
    LinearLayout mActivityJobType;
    private JobTypeAdapter mJobTypeAdapter;
    private List<JobTypeEntity> datas = new ArrayList<>();
    private List<JobTypeEntity> mChildData = new ArrayList<>();
    private List<JobTypeEntity> mParentData = new ArrayList<>();
    private SerializableMap mSelectedMap;
    private String mTitleName;

    @Override
    public int getLayoutId() {
        return R.layout.act_job_type;
    }

    @Override
    public void initPresenter() {
        mPresenter.setVM(this, mModel);
    }

    @Override
    public void initView() {
        Intent intent = getIntent();
        Bundle bundle = intent.getExtras();
        mTitleName = intent.getStringExtra("typeTitleName");
        mSelectedMap = (SerializableMap) bundle.get("map"); // 这个就是我们选中的那个行业和对应的id组成的map
        if (mSelectedMap == null) {
            mSelectedMap = new SerializableMap();
        }
        mJobTypeSelectNumber.setText(this.getResources().getString(R.string.selected_position));
        mTitle.setText(mTitleName);// 进入页面不同标题可能会不同 动态增加标题名字
        mPresenter.getData("zh_version_data.json");
        mJobTypeAdapter = new JobTypeAdapter(this, datas, mParentData, mChildData, mPresenter, mSelectedMap.getMap());
        mListView.setLayoutManager(new LinearLayoutManager(this));
        mListView.setAdapter(mJobTypeAdapter);
        StickyRecyclerHeadersDecoration decoration = new StickyRecyclerHeadersDecoration(mJobTypeAdapter);
        mListView.addItemDecoration(decoration);
        // 头布局点击事件  点击没有效果 不写会出现小问题
        StickyRecyclerHeadersTouchListener touchListener = new StickyRecyclerHeadersTouchListener(mListView, decoration);
        touchListener.setOnHeaderClickListener(new StickyRecyclerHeadersTouchListener.OnHeaderClickListener() {
            @Override
            public void onHeaderClick(View header, int position, long headerId) {
                Log.i("DNLOG", "headerClick");
            }
        });
        mListView.addOnItemTouchListener(touchListener);
        mCheckBoxPositionType.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    mCheckBoxPositionType.setText(getResources().getString(R.string.selected_close));
                    mLinearLayoutAddPositionTypeTxt.setVisibility(View.VISIBLE);
                } else {
                    mCheckBoxPositionType.setText(getResources().getString(R.string.selected_open));
                    mLinearLayoutAddPositionTypeTxt.setVisibility(View.GONE);
                }
            }
        });
        /**
         *  搜索功能 edittext变化监听
         */
        mFilterEdit.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                filterData(s.toString());
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });
        initData();
    }

    /**
     * 搜索 过滤掉不相关的行业
     */
    private void filterData(String filterStr) {
        List<JobTypeEntity> list = new ArrayList<>();
        for (JobTypeEntity model : mChildData) {
            if (model.getJobTypeName().toLowerCase().trim().contains(filterStr.toLowerCase().trim())) {
                list.add(model);
            }
        }
        if (list != null) {
            mJobTypeAdapter.updateListView(list);
        }
    }

    private void initData() {
        if (mSelectedMap != null && mSelectedMap.getMap() != null) {
            final Map<String, Integer> map = mSelectedMap.getMap();
            mLinearLayoutAddPositionTypeTxt.removeAllViews();
            mJobTypeSelectNumber.setText(this.getResources().getString(R.string.selected_position) + map.size() + "/5");
            for (Map.Entry entry : map.entrySet()) {
                final String key = (String) entry.getKey();
                final TextView textViewAddressSelected = new TextView(this);
                textViewAddressSelected.setGravity(Gravity.CENTER | Gravity.LEFT);
                textViewAddressSelected.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
                textViewAddressSelected.setTextColor(getResources().getColor(R.color.F1));
                textViewAddressSelected.setBackgroundResource(R.mipmap.adderss_selected_bg);
                textViewAddressSelected.setText(key);
                textViewAddressSelected.setPadding(20, 5, 20, 5);
                mLinearLayoutAddPositionTypeTxt.addView(textViewAddressSelected);
                textViewAddressSelected.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mLinearLayoutAddPositionTypeTxt.removeView(v);
                        map.remove(key);
                        mJobTypeSelectNumber.setText(JobTypeActivity.this.getResources().getString(R.string.selected_position) + map.size() + "/5");
                        mJobTypeAdapter.notifyData(key);
                    }
                });
            }
        }

    }

    @Override
    public void returnProfessionTypeData(List<JobTypeEntity> data) {
        if (data != null) {
            datas.clear();
            for (JobTypeEntity entity : data) {
                if (entity.getParentId() != 0) {
                    if (entity.getType() == 2) {
                        datas.add(entity);//二级条目
                    } else {
                        mChildData.add(entity); // 三级条目
                    }
                } else {
                    mParentData.add(entity);
                }
            }
            mJobTypeAdapter.notifyDataSetChanged();
        }

    }

    @Override
    public void returnSelectedData(Map<String, Integer> map) {
        mSelectedMap.setMap(map);
        initData();
    }

    @Override
    public void showLoading(String title) {

    }

    @Override
    public void stopLoading() {

    }

    @Override
    public void showErrorTip(String msg) {

    }

    @OnClick({R.id.backBtn, R.id.textOne})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.backBtn:
                finish();
                break;
            case R.id.textOne:  // 确定|保存
                Intent intent = new Intent();
                Bundle bundle = new Bundle();
                bundle.putSerializable("map", mSelectedMap);
                intent.putExtras(bundle);
                this.setResult(200, intent);
                finish();
                break;
        }
    }
}
